<!--
Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

https://www.mall4j.com/

未经允许，不可做商业用途！

版权所有，侵权必究！
-->

<template>
  <!-- 工商信息 -->
  <view class="Mall4j page-store-settings-business">
    <uni-forms
      ref="businessInfoFormRef"
      :model-value="businessInfoForm"
      validate-trigger="submit"
    >
      <view class="setting-info-item">
        <uni-forms-item name="creditCode">
          <view class="title">
            <text class="star">
              *
            </text>
            <text class="txt">
              统一社会信用代码
            </text>
          </view>
          <view class="input-box">
            <uni-easyinput
              v-model="businessInfoForm.creditCode"
              :disabled="isModefyInfor === 0 || isDisabled || (paySettlementType === 1 && baseInfoForm.companyInfoProcessStatus === 2)"
              placeholder="请输入统一社会信用代码"
              maxlength="20"
              @blur="checkInput('creditCode')"
            />
          </view>
        </uni-forms-item>
      </view>
      <view class="setting-info-item">
        <uni-forms-item name="firmName">
          <view class="title">
            <text class="star">
              *
            </text>
            <text class="txt">
              企业名称
            </text>
          </view>
          <view class="input-box">
            <uni-easyinput
              v-model="businessInfoForm.firmName"
              :disabled="isModefyInfor === 0 || isDisabled"
              placeholder="请输入企业名称"
              maxlength="50"
              @blur="checkInput('firmName')"
            />
          </view>
        </uni-forms-item>
      </view>
      <view class="setting-info-item">
        <uni-forms-item name="residence">
          <view class="title">
            <text class="txt">
              住所
            </text>
          </view>
          <view class="input-box">
            <uni-easyinput
              v-if="isModefyInfor !== 0 || businessInfoForm.residence"
              v-model="businessInfoForm.residence"
              :disabled="isModefyInfor === 0 || isDisabled"
              placeholder="请输入住所"
              maxlength="50"
              @blur="checkInput('residence')"
            />
            <text
              v-else
              class="noyet-wrap"
            >
              暂无
            </text>
          </view>
        </uni-forms-item>
      </view>
      <view class="setting-info-item">
        <uni-forms-item name="representative">
          <view class="title">
            <text class="star">
              *
            </text>
            <text class="txt">
              法定代表人
            </text>
          </view>
          <view class="input-box">
            <uni-easyinput
              v-model="businessInfoForm.representative"
              :disabled="isModefyInfor === 0 || isDisabled"
              placeholder="请输入法定代表人"
              maxlength="20"
              @blur="checkInput('representative')"
            />
          </view>
        </uni-forms-item>
      </view>
      <view
        v-if="paySettlementType === 1"
        class="setting-info-item"
      >
        <uni-forms-item name="legalIds">
          <view class="title">
            <text class="star">
              *
            </text>
            <text class="txt">
              法人身份证
            </text>
          </view>
          <view class="input-box">
            <uni-easyinput
              v-model="businessInfoForm.legalIds"
              :disabled="isModefyInfor === 0 || isDisabled"
              placeholder="请输入法定身份证"
              maxlength="20"
              @blur="checkInput('legalIds')"
            />
          </view>
        </uni-forms-item>
      </view>
      <view
        v-if="paySettlementType === 1"
        class="setting-info-item"
      >
        <uni-forms-item name="legalPhone">
          <view class="title">
            <text class="star">
              *
            </text>
            <text class="txt">
              法人手机号
            </text>
          </view>
          <view class="input-box">
            <uni-easyinput
              v-model="businessInfoForm.legalPhone"
              :disabled="isModefyInfor === 0 || isDisabled"
              placeholder="请输入法人手机号"
              maxlength="11"
              @blur="checkInput('legalPhone')"
            />
          </view>
        </uni-forms-item>
      </view>
      <view class="setting-info-item capital">
        <uni-forms-item name="capital">
          <view class="title">
            <text class="txt">
              注册资本
            </text>
          </view>
          <view class="input-box">
            <block v-if="isModefyInfor !== 0 || businessInfoForm.capital">
              <uni-easyinput
                v-model="businessInfoForm.capital"
                :disabled="isModefyInfor === 0 || isDisabled"
                type="number"
                placeholder="请输入注册资本"
                @blur="checkInput('capital')"
              />
              <view class="unit">
                万元
              </view>
            </block>
            <text
              v-else
              class="noyet-wrap"
            >
              暂无
            </text>
          </view>
        </uni-forms-item>
      </view>
      <view class="setting-info-item business-date">
        <uni-forms-item name="foundTime">
          <view class="title">
            <text class="txt">
              成立日期
            </text>
          </view>
          <view
            v-if="isModefyInfor !== 0"
            class="input-box"
            @tap="handleSelect(-1)"
          >
            <view
              class="input-content"
              :class="{ 'input-placeholder': !businessInfoForm.foundTime }"
            >
              {{ businessInfoForm.foundTime || '选择成立日期' }}
            </view>
            <view
              v-if="businessInfoForm.foundTime"
              class="foundTime-clear-icon"
              @tap.stop="businessInfoForm.foundTime = null"
            />
            <image
              src="/static/images/date-icon.png"
              class="date-icon"
            />
          </view>
          <view
            v-else-if="businessInfoForm.foundTime"
            class="input-box"
          >
            <text>{{ businessInfoForm.foundTime }}</text>
          </view>
          <view
            v-else
            class="input-box"
          >
            <text class="noyet-wrap">
              暂无
            </text>
          </view>
        </uni-forms-item>
      </view>
      <view class="setting-info-item business-date">
        <uni-forms-item name="timeRange">
          <view class="title">
            <text class="txt">
              营业日期
            </text>
          </view>
          <view
            v-if="isModefyInfor !== 0"
            class="input-box"
          >
            <view @tap="handleSelect(1)">
              <view
                class="input-content date-int"
                :class="{ 'input-placeholder': !businessInfoForm.startTime }"
              >
                {{ businessInfoForm.startTime || '开始时间' }}
              </view>
            </view>
            <icon
              v-if="businessInfoForm.startTime"
              type="clear"
              size="18"
              style="margin-left:auto;"
              @tap="clearStartTime"
            />
            <view class="to">
              至
            </view>
            <view @tap="handleSelect(0)">
              <view
                class="input-content date-int endTime"
                :class="{ 'input-placeholder': !businessInfoForm.endTime && !endTimeFlag }"
              >
                {{ endTimeFlag && !businessInfoForm.endTime ? '无固定期限' : businessInfoForm.endTime || '结束时间' }}
              </view>
            </view>
            <icon
              v-if="businessInfoForm.endTime"
              type="clear"
              size="18"
              style="margin-left:auto;"
              @tap="clearEndTime"
            />
            <image
              :style="{ marginLeft: businessInfoForm.endTime ? '20rpx' : 'auto' }"
              src="/static/images/date-icon.png"
              class="date-icon"
            />
          </view>
          <view
            v-else
            class="input-box"
          >
            <span v-if="businessInfoForm.startTime">
              {{ businessInfoForm.startTime }} - {{ businessInfoForm.endTime || '无固定期限' }}
            </span>
            <span
              v-else
              class="noyet-wrap"
            >
              暂无
            </span>
          </view>
        </uni-forms-item>
      </view>
      <view class="setting-info-item">
        <uni-forms-item name="businessScope">
          <view class="title">
            <text class="star">
              *
            </text>
            <text class="txt">
              经营范围
            </text>
          </view>
          <view class="textarea-box">
            <textarea
              v-model="businessInfoForm.businessScope"
              :disabled="isModefyInfor === 0 || isDisabled"
              placeholder="请输入经营范围"
              maxlength="500"
              @blur="checkInput('businessScope')"
            />
          </view>
        </uni-forms-item>
      </view>
      <!-- 身份证证件照 -->
      <view class="setting-info-item">
        <view class="title">
          <text class="star">
            *
          </text>
          <text class="txt">
            法人身份证
          </text>
        </view>
        <view class="id-upload-image">
          <uni-forms-item
            name="identityCardFront"
            class="id-front"
          >
            <view
              v-if="isModefyInfor !== 0"
              class="upload-image"
            >
              <view class="upload-con">
                <view
                  v-if="!businessInfoForm.identityCardFront"
                  class="upload-btn"
                  @tap="uploadImg('identityCardFront')"
                >
                  <view class="up-text text-btn">
                    +添加
                  </view>
                  <view class="up-text">
                    上传身份证人像面
                  </view>
                </view>
                <view
                  v-if="businessInfoForm.identityCardFront"
                  class="upload-con"
                  @tap.stop="previewImg(businessInfoForm.identityCardFront)"
                >
                  <image
                    :src="util.checkFileUrl(businessInfoForm.identityCardFront)"
                    mode="aspectFit"
                    class="up-img-con"
                  />
                  <view
                    v-if="!isDisabled"
                    class="del-btn"
                    @tap.stop="delLoadImg('identityCardFront')"
                  />
                </view>
              </view>
            </view>
            <view
              v-else
              class="upload-image"
            >
              <view
                v-if="businessInfoForm.identityCardFront"
                class="upload-con"
              >
                <image
                  :src="util.checkFileUrl(businessInfoForm.identityCardFront)"
                  mode="aspectFit"
                  class="up-img-con"
                />
              </view>
            </view>
          </uni-forms-item>
          <uni-forms-item name="identityCardLater">
            <view
              v-if="isModefyInfor !== 0"
              class="upload-image"
            >
              <view class="upload-con">
                <view
                  v-if="!businessInfoForm.identityCardLater"
                  class="upload-btn"
                  @tap="uploadImg('identityCardLater')"
                >
                  <view class="up-text text-btn">
                    +添加
                  </view>
                  <view class="up-text">
                    上传身份证国徽面
                  </view>
                </view>
                <view
                  v-if="businessInfoForm.identityCardLater"
                  class="upload-con"
                  @tap.stop="previewImg(businessInfoForm.identityCardLater)"
                >
                  <image
                    :src="util.checkFileUrl(businessInfoForm.identityCardLater)"
                    mode="aspectFit"
                    class="up-img-con"
                  />
                  <view
                    v-if="!isDisabled"
                    class="del-btn"
                    @tap.stop="delLoadImg('identityCardLater')"
                  />
                </view>
              </view>
            </view>
            <view
              v-else
              class="upload-image"
            >
              <view class="upload-con">
                <view
                  v-if="businessInfoForm.identityCardLater"
                  class="upload-con"
                >
                  <image
                    :src="util.checkFileUrl(businessInfoForm.identityCardLater)"
                    mode="aspectFit"
                    class="up-img-con"
                  />
                </view>
              </view>
            </view>
          </uni-forms-item>
        </view>
      </view>
      <!-- 营业执照电子版 -->
      <view class="setting-info-item">
        <uni-forms-item name="businessLicense">
          <view class="title">
            <text class="star">
              *
            </text>
            <text class="txt">
              营业执照电子版
            </text>
          </view>
          <view
            v-if="isModefyInfor !== 0"
            class="upload-image bus-license"
          >
            <view class="upload-con">
              <view
                v-if="!businessInfoForm.businessLicense"
                class="upload-btn"
                @tap="uploadImg('businessLicense')"
              >
                <view class="up-text text-btn">
                  +添加
                </view>
                <view class="up-text">
                  上传文字清晰的照片，露出边框和国徽
                </view>
              </view>
              <view
                v-if="businessInfoForm.businessLicense"
                class="upload-con"
                @tap.stop="previewImg(businessInfoForm.businessLicense)"
              >
                <image
                  :src="util.checkFileUrl(businessInfoForm.businessLicense)"
                  mode="heightFix"
                  class="up-img-con "
                />
                <view
                  v-if="!isDisabled"
                  class="del-btn"
                  @tap.stop="delLoadImg('businessLicense')"
                />
              </view>
            </view>
          </view>
          <view
            v-else
            class="upload-image bus-license"
          >
            <view class="upload-con">
              <view
                v-if="businessInfoForm.businessLicense"
                class="upload-con"
              >
                <image
                  :aa="util.checkFileUrl(businessInfoForm.businessLicense)"
                  :src="util.checkFileUrl(businessInfoForm.businessLicense)"
                  mode="heightFix"
                  class="up-img-con "
                />
              </view>
            </view>
          </view>
        </uni-forms-item>
      </view>

      <view
        v-if="util.isAuthorities('shop:shopCompany:save') && baseInfoForm.shopStatus !== 5"
        class="footer"
      >
        <button
          v-if="(isModefyInfor!==0 && paySettlementType !== 1) || (paySettlementType===1 && (isModefyInfor!==0 || baseInfoForm.companyInfoProcessStatus===3 && baseInfoForm.companyInfoProcessStatus===0) && baseInfoForm.companyInfoProcessStatus!==1)"
          class="button"
          type="default"
          hover-class="none"
          @tap="submit"
        >
          修改
        </button>
        <button
          v-if="(businessInfoForm.edit && paySettlementType!==1) || (paySettlementType===1 && businessInfoForm.edit && baseInfoForm.companyInfoProcessStatus!==0)"
          type="default"
          class="button"
          hover-class="none"
          @tap="showModifyInfor"
        >
          查看修改信息
        </button>
        <view
          v-if="paySettlementType===1 && baseInfoForm.idCardCollectProcessStatus!==4 && (baseInfoForm.shopStatus===3 || baseInfoForm.shopStatus===5)"
          class="refresh-btn"
          @tap="onDataUpdate"
        >
          <image
            class="refresh-img"
            src="../../static/images/refresh.png"
          />
          数据更新
        </view>
      </view>

      <date-popup
        v-if="showDatePopup"
        :type="datePopupType"
        :vaule="datePopupVal"
        format="YYYY-MM-DD"
        @handle-date="handleDate"
        @cancal="closeDatePopup"
      />
    </uni-forms>
  </view>
</template>
<!-- eslint-disable n/no-callback-literal -->

<script setup>
import { reactive } from 'vue'
import dayjs from 'dayjs'
import { checkIDCard } from '@/utils/validate.js'
import util from '@/utils/util'
const paySettlementType = uni.getStorageSync('bbcPaySettlementType')

const Data = reactive({
  // 是否已有提交
  isModefyInfor: false,
  // 工商信息
  businessInfoForm: {
    creditCode: '',
    firmName: '',
    residence: '',
    representative: '',
    legalPhone: '',
    legalIds: '',
    capital: null,
    foundTime: '',
    businessScope: '',
    startTime: '',
    endTime: '',
    identityCardFront: '',
    identityCardLater: '',
    businessLicense: ''
  },
  endTimeFlag: true,
  rules: {
    creditCode: {
      rules: [
        { required: true, errorMessage: '请输入统一社会信用代码' },
        {
          validateFunction: (rule, value, data, callback) => {
            const reg = /^(([0-9A-Za-z]{15})|([0-9A-Za-z]{18})|([0-9A-Za-z]{20}))$/
            if (!reg.test(value)) {
              callback('请输入正确的统一社会信用代码')
              return false
            }
          }
        }
      ]
    },
    firmName: {
      rules: [{ required: true, errorMessage: '请输入企业名称' }]
    },
    representative: {
      rules: [{ required: true, errorMessage: '请输入法定代表人' }]
    },
    businessScope: {
      rules: [
        { required: true, errorMessage: '请输入经营范围' },
        {
          validateFunction: (rules, value, data, callBack) => {
            if (!Data.businessInfoForm.businessScope.trim()) {
              callBack('请输入经营范围')
              return false
            }
          }
        }
      ]
    },
    identityCardFront: {
      rules: [
        { required: true, errorMessage: '请上传身份证人像面' },
        {
          validateFunction: (rule, value, data, callback) => {
            if (Data.businessInfoForm.identityCardFront.trim().length === 0) {
              callback('请上传身份证人像面')
              return false
            }
          }
        }
      ]
    },
    identityCardLater: {
      rules: [
        { required: true, errorMessage: '请上传身份证国徽面' },
        {
          validateFunction: (rule, value, data, callback) => {
            if (Data.businessInfoForm.identityCardLater.trim().length === 0) {
              callback('请上传身份证国徽面')
              return false
            }
          }
        }
      ]
    },
    businessLicense: {
      rules: [
        { required: true, errorMessage: '请上传营业执照电子版' },
        {
          validateFunction: (rule, value, data, callback) => {
            if (Data.businessInfoForm.businessLicense.trim().length === 0) {
              callback('请上传营业执照电子版')
              return false
            }
          }
        }]
    },
    legalPhone: {
      rules: [
        { required: true, errorMessage: '请输入联系方式' },
        {
          validateFunction: (rule, value, data, callback) => {
            const reg = /^(?:(?:\+|00)86)?1\d{2}([\d*]{4})\d{4}$/
            if (!reg.test(value)) {
              callback('请输入正确的联系方式')
              return false
            }
          }
        }
      ]
    },
    legalIds: {
      rules: [
        { required: true, errorMessage: '法人身份证不能为空' },
        {
          validateFunction: (rule, value, data, callback) => {
            if (!value || !checkIDCard(value)) {
              callback('请输入正确的法人身份证')
              return false
            }
          }
        }
      ]
    }
  },
  // 成立日期
  foundTime: '',
  // day：自然日，month： 自然月
  datePopupType: 'day',
  // 选择日期弹窗
  showDatePopup: false,
  // 日期
  datePopupVal: '',
  // 当前选择日期类型 -1成立日期 0结束日期 1开始日期
  curSelDateType: -1,

  baseInfoForm: {
    shopStatus: 0,
    companyInfoProcessStatus: -1
  },
  shopAuditStatus: {}
})

const { isModefyInfor, businessInfoForm, endTimeFlag, datePopupType, showDatePopup, datePopupVal, baseInfoForm } = toRefs(Data)

const isDisabled = computed(() => {
  return Data.shopAuditStatus.status === 0 && paySettlementType === 1 && Data.baseInfoForm.companyInfoProcessStatus === 3
})

onLoad(() => {
  getShopCompany()
  if (paySettlementType === 1) {
    onGetAuditingInfo()
  }
})

onShow(() => {
  getShopDetailnfo()
  isModifyInfor()
})

const businessInfoFormRef = ref()
onReady(() => {
  businessInfoFormRef.value.setRules(Data.rules)
})

/**
* 获取店铺信息
*/
const getShopDetailnfo = () => {
  http.request({
    url: '/shop/shopDetail/info',
    method: 'GET'
  }).then(({ data }) => {
    Data.baseInfoForm = data
  })
}

/**
* 查看修改信息
*/
const showModifyInfor = () => {
  uni.navigateTo({
    url: '/package-settings/pages/modify-infor/modify-infor'
  })
}

/**
* 提交修改休息
*/
const modifyInfor = () => {
  const data = Object.assign({}, Data.businessInfoForm)
  data.foundTime = data.foundTime ? dayjs(data.foundTime).format('YYYY-MM-DD HH:mm:ss') : data.foundTime
  data.startTime = data.startTime ? dayjs(data.startTime).format('YYYY-MM-DD HH:mm:ss') : data.startTime
  data.endTime = data.startTime ? data.endTime ? dayjs(data.endTime).format('YYYY-MM-DD HH:mm:ss') : null : data.startTime

  http.request({
    url: '/shop/companyAuditing/applyChangeCompanyInfo',
    method: 'post',
    data
  }).then(() => {
    uni.showToast({
      title: '提交工商信息审核成功',
      icon: 'none',
      duration: 1500,
      complete: () => {
        if (paySettlementType === 1 && (Data.baseInfoForm.companyInfoProcessStatus === 0 || Data.baseInfoForm.companyInfoProcessStatus === 3)) {
          setTimeout(() => {
            uni.redirectTo({
              url: '/package-settings/pages/allinpay-store-account/allinpay-store-account'
            })
          }, 1500)
        }
      }
    })
    getShopCompany()
    isModifyInfor()
    getShopDetailnfo()
  })
}

/**
* 判断有无 提交审核信息
*/
const isModifyInfor = () => {
  http.request({
    url: '/shop/companyAuditing/auditInfo',
    method: 'GET'
  }).then(({ data }) => {
    Data.isModefyInfor = data.status
  })
}

/**
* 选择日期
* @param {Number} curSelDateType -1成立日期 0结束日期 1开始日期
*/
const handleSelect = (curSelDateType) => {
  if (isDisabled.value) {
    return
  }
  switch (curSelDateType) {
    case -1:
      // 成立日期
      Data.datePopupVal = Data.businessInfoForm.foundTime
      break
    case 0:
      if (!Data.businessInfoForm.startTime) {
        uni.showToast({
          title: '请先选择开始时间',
          icon: 'none',
          duration: 1500
        })
        return
      }
      Data.endTimeFlag = false
      // 营业期限-结束日期
      Data.datePopupVal = Data.businessInfoForm.endTime
      break
    case 1:
      // 营业期限-开始日期
      Data.datePopupVal = Data.businessInfoForm.startTime
      break
    default:
      Data.datePopupVal = ''
      break
  }
  Data.datePopupVal = Data.datePopupVal ? dayjs(Data.datePopupVal).format('YYYY-MM-DD HH:mm:ss') : dayjs().format('YYYY-MM-DD HH:mm:ss')
  Data.curSelDateType = curSelDateType
  Data.showDatePopup = true
}

/**
* 输入框空格校验
*/
const checkInput = (type) => {
  const reg = /^\s+$/g
  if (type === 'creditCode' && reg.test(Data.businessInfoForm.creditCode)) {
    Data.businessInfoForm.creditCode = ''
  }
  if (type === 'firmName' && reg.test(Data.businessInfoForm.firmName)) {
    Data.businessInfoForm.firmName = ''
  }
  if (type === 'residence' && reg.test(Data.businessInfoForm.residence)) {
    Data.businessInfoForm.residence = ''
  }
  if (type === 'representative' && reg.test(Data.businessInfoForm.representative)) {
    Data.businessInfoForm.representative = ''
  }
  if (type === 'capital') {
    if (reg.test(Data.businessInfoForm.capital)) {
      Data.businessInfoForm.capital = ''
    }
    // 校验数额
    validationAmount()
  }
  if (type === 'businessScope' && reg.test(Data.businessInfoForm.businessScope)) {
    Data.businessInfoForm.businessScope = ''
  }
  if (type === 'legalPhone' && reg.test(Data.businessInfoForm.legalPhone)) {
    Data.baseInfoForm.legalPhone = ''
  }
  if (type === 'legalIds' && reg.test(Data.businessInfoForm.legalIds)) {
    Data.baseInfoForm.legalIds = ''
  }
}

/**
* 注册资本金额校验
*/
const validationAmount = () => {
  const capital = Data.businessInfoForm.capital
  if (capital) {
    Data.businessInfoForm.capital = checkNum(capital)
    if (Number.parseFloat(Data.businessInfoForm.capital) === 0) {
      Data.businessInfoForm.capital = 0
    }
    if (Number.parseFloat(Data.businessInfoForm.capital) > 99999999) {
      Data.businessInfoForm.capital = 99999999
    }
  }
}

/**
* input输入框只允许输入正数和小数(保留小数点后两位)
*/
const checkNum = (num) => {
  if (num) {
    let tmpVal = num.replace(/[^\d^\\.]/g, '')
    const reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/ // 最多允许后输入两位小数
    if (!reg.test(tmpVal)) {
      tmpVal = tmpVal + ''
      tmpVal = tmpVal.substring(0, tmpVal.indexOf('.') + 3)
      const n = (tmpVal.split('.')).length - 1
      if (n > 1) {
        tmpVal = tmpVal.substring(0, tmpVal.indexOf('.'))
      }
    }
    return tmpVal
  } else {
    return ''
  }
}

/**
* 获取日期选择数据
*/
const handleDate = (data) => {
  data.format = data.format ? data.format : data.data ? dayjs(data.data).format('YYYY-MM-DD') : null
  switch (Data.curSelDateType) {
    case -1:
      // 成立日期
      // Data.foundTime = data.format
      Data.businessInfoForm.foundTime = data.format
      break
    case 0:
      // 营业期限-结束日期
      if (Data.businessInfoForm.startTime && Date.parse(Data.businessInfoForm.startTime) >= Date.parse(data.data)) {
        uni.showToast({
          title: '结束日期需晚于开始日期',
          mask: true,
          icon: 'none',
          duration: 1500
        })
        return
      }
      // Data.businessInfoForm.timeRange[1] = data.format
      Data.businessInfoForm.endTime = data.format
      break
    case 1:
      // 营业期限-开始日期
      if (Data.businessInfoForm.endTime && Date.parse(Data.businessInfoForm.endTime) <= Date.parse(data.data)) {
        uni.showToast({
          title: '开始日期需早于结束日期',
          mask: true,
          icon: 'none',
          duration: 1500
        })
        return
      }
      // Data.businessInfoForm.timeRange[0] = data.format
      Data.businessInfoForm.startTime = data.format
      break
    default:
      break
  }
  closeDatePopup()
}

/**
* 关闭选择日期弹窗
*/
const closeDatePopup = () => {
  Data.showDatePopup = false
}

/**
* 提交表单
*/
const submit = () => {
  businessInfoFormRef.value.validate().then(() => {
    modifyInfor()
  })
}

/**
* 获取工商信息
*/
const getShopCompany = () => {
  http.request({
    url: '/shop/shopCompany',
    method: 'GET'
  }).then(({ data: res }) => {
    Data.endTimeFlag = true
    res.foundTime = res.foundTime ? dayjs(res.foundTime).format('YYYY-MM-DD') : res.foundTime
    res.startTime = res.startTime ? dayjs(res.startTime).format('YYYY-MM-DD') : res.startTime
    res.endTime = res.endTime ? dayjs(res.endTime).format('YYYY-MM-DD') : res.endTime
    Data.businessInfoForm = { ...Data.businessInfoForm, ...res }
  })
}

/**
* 上传图片
* @param {String} type
*/
const uploadImg = (type) => {
  // #ifdef APP-PLUS
  uni.chooseImage({
    count: 1, // 默认9
    sizeType: ['compressed'],
    sourceType: ['album'],
    success: (res) => {
      const tempFilePaths = res.tempFilePaths[0]
      // 上传图片
      http.request({
        url: '/admin/file/getPreSignUrl',
        method: 'GET',
        data: { fileName: res.tempFiles[0].name, isImFile: false }
      }).then(({ data }) => {
        util.plusIo(tempFilePaths).then((buffer) => {
          uni.request({
            url: data.preSignUrl,
            method: 'PUT',
            data: buffer,
            success: function () {
              http.request({
                url: '/admin/file/uploadSuccess',
                method: 'PUT',
                data: [
                  {
                    fileId: data.fileId,
                    attachFileGroupId: 0,
                    type: 1,
                    fileSize: res.tempFiles[0].size
                  }
                ]
              }).then((responseData) => {
                if (responseData.code === '00000') {
                  attachFilePage(data.fileId).then((data) => { // 根据上传传图片id 获取文件路径
                    switch (type) {
                      case 'identityCardFront':
                        Data.businessInfoForm.identityCardFront = data.records[0].filePath // 上传身份证人像面
                        break
                      case 'identityCardLater': // 上传身份证国徽面
                        Data.businessInfoForm.identityCardLater = data.records[0].filePath
                        break
                      case 'businessLicense': // 营业执照电子版
                        Data.businessInfoForm.businessLicense = data.records[0].filePath
                        break
                      default:
                        break
                    }
                  })
                } else {
                  uni.showToast({
                    title: '上传失败',
                    icon: 'none'
                  })
                }
              })
            },
            fail: function () {
              uni.hideLoading()
            }
          })
        })
      })
    }
  })
  // #endif
  // #ifdef H5
  uni.chooseImage({
    count: 1, // 默认9
    sizeType: ['compressed'],
    sourceType: ['album'],
    success: (res) => {
      const tempFilePaths = res.tempFilePaths[0] // 图片的本地临时文件路径列表
      // 上传图片
      http.request({
        url: '/admin/file/getPreSignUrl',
        method: 'GET',
        data: { fileName: res.tempFiles[0].name, isImFile: false }
      }).then(({ data }) => {
        uni.request({
          url: tempFilePaths,
          method: 'GET',
          responseType: 'arraybuffer',
          success: function (requestRes) {
            uni.request({
              url: data.preSignUrl,
              method: 'PUT',
              data: requestRes.data,
              success: function () {
                http.request({
                  url: '/admin/file/uploadSuccess',
                  method: 'PUT',
                  data: [
                    {
                      fileId: data.fileId,
                      attachFileGroupId: 0,
                      type: 1,
                      fileSize: res.tempFiles[0].size
                    }
                  ]
                }).then((responseData) => {
                  if (responseData.code === '00000') {
                    attachFilePage(data.fileId).then((data) => { // 根据上传传图片id 获取文件路径
                      switch (type) {
                        case 'identityCardFront': // 上传身份证人像面
                          Data.businessInfoForm.identityCardFront = data.records[0].filePath
                          break
                        case 'identityCardLater': // 上传身份证国徽面
                          Data.businessInfoForm.identityCardLater = data.records[0].filePath
                          break
                        case 'businessLicense':
                          Data.businessInfoForm.businessLicense = data.records[0].filePath // 营业执照电子版
                          break
                        default:
                          break
                      }
                    })
                  } else {
                    uni.showToast({
                      title: '上传失败',
                      icon: 'none'
                    })
                  }
                })
              },
              fail: function () {
                uni.hideLoading()
              }
            })
          }
        })
      })
    }
  })
  // #endif
}
const attachFilePage = (fileId) => {
  return new Promise(resolve => {
    // 根据上传传图片id 获取文件路径
    http.request({
      url: '/admin/file/attachFilePage',
      method: 'get',
      data: {
        fileId,
        current: 1,
        size: 1,
        type: 1
      }
    }).then(({ data }) => {
      resolve(data)
    })
  })
}
/**
*  图片预览
*/
const previewImg = (src) => {
  // console.log(1111, src)
  uni.previewImage({
    urls: [src]
  })
}

/**
* 删除图片
*
*/
const delLoadImg = (type) => {
  Data.businessInfoForm[type] = ''
}

const clearStartTime = () => {
  Data.businessInfoForm.startTime = ''
  Data.businessInfoForm.endTime = ''
}

const clearEndTime = () => {
  Data.endTimeFlag = false
  Data.businessInfoForm.endTime = ''
}

/**
 * 获取审核状态
 */
const onGetAuditingInfo = () => {
  http.request({
    url: '/shop/shopDetail/getAuditingInfo',
    method: 'GET'
  }).then(({ data }) => {
    Data.shopAuditStatus = data
  })
}
const onDataUpdate = () => {
  http.request({
    url: '/shop/shopCompany/updateIdCardStatus',
    method: 'PUT'
  }).then(({ data }) => {
    if (data === 4) {
      // 审核成功刷新页面
      uni.redirectTo({
        url: '/package-settings/pages/store-settings-business/store-settings-business'
      })
    } else if (data === 0 || data === 2 || data === 3) {
      // 审核失败，弹窗让用户重新上传
      uni.redirectTo({
        url: '/package-settings/pages/business-info-reupload/business-info-reupload'
      })
    } else if (data === 1) {
      getShopCompany()
    }
  })
}
</script>

<style lang="scss" scoped>
@use "store-settings-business";
</style>
